// pages/push/push.js
import config from '../../utils/consts.js'
import upload from '../../utils/upload.js'
var app = getApp()
var dateTimePicker = require('../../utils/dateTimePicker.js');
var slimglist2 = [] // 临时缩略图数组
Page({
  /**
   * 页面的初始数据
   */
  data: {
    setInter: '',
    actTab: '0', //0是新闻1是活动
    url: app.data.imgUrl,
    picList: [], //原图
    picList2: [], //缩略图
    videoSrc: '',
    videoCover: '',
    params: {
      pic1: '', //原图
      pic2: '',
      pic3: '',
      pic4: '',
      pic5: '',
      pic6: '',
      pic7: '',
      pic8: '',
      pic9: '',
      sic1: '', //缩略
      sic2: '',
      sic3: '',
      sic4: '',
      sic5: '',
      sic6: '',
      sic7: '',
      sic8: '',
      sic9: '',

      video: '',
      cover: '',
      title: '',
      id: '',
      newsType: 0,
      auth: "0",
      activityAuth: "0",
      content: '',
      location: '',

    },
    pushNews: 'pushNews', //是否发布
    userSelect: '',
    imgSheet: ['图片'],
    videoSheet: ['视频'],
    startData: '',
    endData: '',
    operationIs: '', //编辑类型
    dateTimeArray: null,
    dateTime: null,
    dateTimeArray1: null,
    dateTime1: null,
    isEdit: false, // 是否是编辑状态，如果是就不显示删除图片或视频的按钮
    leftpx: '0rpx',
    contentStatus: '发布成功', //根据是否需要审核而显示的提示
    canvasImageFilePath: '',
    // canvasWidth:336,
    // canvasHeight:336
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.operation) {
      this.setData({
        operationIs: options.operation
      })
    }
    let id = options.id
    // 获取完整的年月日 时分秒，以及默认显示的数组
    var obj = dateTimePicker.dateTimePicker();
    var dt = obj.dateTime,
      dta = obj.dateTimeArray
    var startData = dta[0][dt[0]] + '-' + dta[1][dt[1]] + '-' + dta[2][dt[2]] + ' ' + dta[3][dt[3]] + ':' + dta[4][dt[4]]
    // var startData = dta[0][dt[0]] + '-' + dta[1][dt[1]] + '-' + dta[2][dt[2]] + ' ' + dta[3][dt[3]] + ':' + dta[4][dt[4]] + ':' + dta[5][dt[5]]
    this.setData({
      dateTime: obj.dateTime,
      dateTimeArray: obj.dateTimeArray,
      dateTime1: obj.dateTime,
      dateTimeArray1: obj.dateTimeArray,
      startData: startData,
      endData: startData,
    })
    //如果存在id，则是从其他页面跳转进来的
    if (options.id) {
      this.setData({
        'params.id': id,
        isEdit: true
      })
      //根据id获取详细内容
      this.getDetail(options.id)
    }
  },
  //根据id获取详细内容
  getDetail(id) {
    wx.teamApi.news.detail(id).then(res => {
      if (res.data.errcode === 0) {
        let ct = res.data.result.content
        let p = this.data.params
        for (let i = 1; i < 10; i++) {
          if (ct['pic' + i]) {
            this.data.picList.push(ct['pic' + i])
          }
        }
        p.pic1 = ct.pic1
        p.pic2 = ct.pic2
        p.pic3 = ct.pic3
        p.pic4 = ct.pic4
        p.pic5 = ct.pic5
        p.pic6 = ct.pic6
        p.pic7 = ct.pic7
        p.pic8 = ct.pic8
        p.pic9 = ct.pic9
        p.video = ct.video || ''
        p.cover = ct.cover
        p.title = ct.title
        p.content = ct.content
        p.id = ct.id
        p.newsType = ct.newsType
        p.location = ct.location || ''
        p.auth = ct.auth.toString()
        p.activityAuth = ct.activityAuth.toString()
        if (ct.cover) {
          this.data.userSelect = 'video'
        } else if (this.data.picList.length > 0) {
          this.data.userSelect = 'img'
        }
        this.setData({
          startData: ct.startDate,
          endData: ct.endDate,
          params: p,
          actTab: ct.newsType,
          picList: this.data.picList,
          videoCover: ct.cover,
        })
      } else {
        wx.showModal({
          title: '提示',
          content: res.data.err,
          success: () => {
            wx.navigateBack()
          }
        })
      }
    })
  },
  //改变创建时间
  changeDateTime(e) {
    this.setData({
      dateTime: e.detail.value
    });
  },
  //开始时间
  changeDateTimeColumn(e) {
    var arr = this.data.dateTime,
      dateArr = this.data.dateTimeArray;

    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);

    var dateTimeArray = dateArr,
      dateTime = arr
    var startData = dateTimeArray[0][dateTime[0]] + '-' + dateTimeArray[1][dateTime[1]] + '-' + dateTimeArray[2][dateTime[2]] + ' ' + dateTimeArray[3][dateTime[3]] + ':' + dateTimeArray[4][dateTime[4]]
    this.setData({
      dateTimeArray: dateArr,
      dateTime: arr,
      startData: startData
    });
  },
  changeDateTime1(e) {
    this.setData({
      dateTime1: e.detail.value
    });
  },
  changeDateTimeColumn1(e) { //结束时间
    var arr = this.data.dateTime,
      dateArr = this.data.dateTimeArray;

    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);

    var dateTimeArray = dateArr,
      dateTime = arr
    var endData = dateTimeArray[0][dateTime[0]] + '-' + dateTimeArray[1][dateTime[1]] + '-' + dateTimeArray[2][dateTime[2]] + ' ' + dateTimeArray[3][dateTime[3]] + ':' + dateTimeArray[4][dateTime[4]]
    this.setData({
      dateTimeArray1: dateArr,
      dateTime1: arr,
      endData: endData
    });
  },
  //发布新闻或活动
  pushNews() {
    if (this.data.params.title.length <= 0) {
      wx.showToast({
        title: '请填写标题',
        icon: 'none'
      })
      return
    }
    if (this.data.params.content.length <= 0) {
      wx.showToast({
        title: '请输入内容',
        icon: 'none'
      })
      return
    }
    if (this.data.params.newsType == 1) {
      if (this.data.endData <= this.data.startData) {
        wx.showModal({
          title: '提示',
          content: '结束时间必须大于开始时间'
        })
        return
      }
      if (this.data.params.location.length < 1) {
        wx.showModal({
          title: '提示',
          content: '请输入活动地址'
        })
        return
      }
      this.data.params.startDate = this.data.startData
      this.data.params.endDate = this.data.endData
      // wx.showToast({
      //   title: '结束时间必须大于开始时间',
      //   icon: 'none'
      // })
    }
    this.setData({
      params: this.data.params,
      pushNews: ''
    })
    wx.showLoading({
      title: '正在发布中...',
      mask: true
    })
    if (this.data.params.id) {
      this.pushNewsStep2()
    } else {
      if (this.data.userSelect === 'img') {
        this.getCanvasImg(0, 0, this.data.picList, (slimglist) => {
          console.log(slimglist, 'slt')
          //上传缩略图
          upload.uploadImg(slimglist).then(slupres => {
            console.log(slupres, 'slt----')
            slupres.forEach((item, index) => {
              this.data.params['sic' + (index + 1)] = item.Location
            })
            //上传高清图片
            upload.uploadImg(this.data.picList).then(upres => {
              upres.forEach((item, index) => {
                this.data.params['pic' + (index + 1)] = item.Location
              })

              this.pushNewsStep2()
            })
          })
        })
      } else if (this.data.userSelect === 'video') {
        upload.uploadVideo(this.data.videoSrc, this.data.videoCover).then(upres => {
          console.log('242')
          console.log(upres)
          this.data.params.video = upres.src
          this.data.params.cover = upres.cover
          this.pushNewsStep2()
        })
      } else {
        this.pushNewsStep2()
      }
    }

    console.log('275')
    console.log(this.data.picList2)
  },
  //压缩并获取图片，这里用了递归的方法来解决canvas的draw方法延时的问题
  getCanvasImg(index, failNum, tempFilePaths, cb) {
    if (index < tempFilePaths.length) {
      //获取图片信息   
      wx.getImageInfo({
        src: tempFilePaths[index], //图片链接
        success: (res) => {
          //缩放比例
          var setWidth, setHeight
          if (res.width / res.height >= 336 / 336) {
            if (res.width > 336) {
              setWidth = 336
              setHeight = (res.height * 336) / res.width
            } else {
              setWidth = res.width
              setHeight = res.height
            }
          } else {
            if (res.height > 336) {
              setHeight = 336
              setWidth = (res.width * 336) / res.height
            } else {
              setWidth = res.width
              setHeight = res.height
            }
          }
          const ctx = wx.createCanvasContext('attendCanvasId', this)
          ctx.drawImage(tempFilePaths[index], 0, 0, setWidth, setHeight)
          ctx.draw(true, () => {
            index = index + 1
            wx.canvasToTempFilePath({ //把当前画布指定区域的内容导出生成指定大小的图片。
              canvasId: 'attendCanvasId',
              width: setWidth,
              height: setHeight,
              destWidth: setWidth, //指定图片宽度
              destHeight: setHeight, //指定图片高度
              fileType: 'jpg', //指定文件类型
              quality: 0.1,
              success: (res) => {
                console.log(res, 'sl', slimglist2, tempFilePaths.length)
                slimglist2.push(res.tempFilePath)
                if (slimglist2.length >= tempFilePaths.length) {
                  cb(slimglist2)
                } else {
                  setTimeout(() => { this.getCanvasImg(index, failNum, tempFilePaths, cb) }, 100)
                }

              }
            }, this)
          })
        }
      })
    }
  },
  uploadCanvasImg(tempFilePath) {
    var test = ''
    upload.uploadImg(tempFilePath).then(upres => {
      upres.forEach((item, index) => {
        test = item.Location
        this.data.picList2.push(test) //插入缩略图
      })
    })
  },




  //上传发布内容事件
  pushNewsStep2() {
    console.log('348')
    console.log(this.data.params)
    wx.teamApi.news.adminReleaseNews(this.data.params).then(res => {
      this.setData({
        pushNews: 'pushNews'
      })
      wx.hideLoading()
      if (res.data.errcode === 0) {
        if (!app.globalData.approvalstatus) { //判断是否需要通过审核
          this.setData({
            contentStatus: '等待审核通过...'
          })
        } else {
          this.setData({
            contentStatus: '发布成功！'
          })
        }
        wx.showModal({
          title: '成功',
          content: this.data.contentStatus,
          showCancel: false,
          success: (act) => {
            wx.switchTab({
              url: '../index/index',
            })
          }
        })
        //发布成功打上标识
        app.globalData.pushStatus = true

      }
    })
  },
  remove(e) {
    let index = e.currentTarget.dataset.index
    this.data.picList.splice(index, 1)
    this.data.picList2.splice(index, 1)
    if (this.data.picList.length === 0) { // 如果图片列表一张图片都没得了，需要重新选择上传视频还是图片
      this.data.userSelect = ''
    }
    this.setData({
      picList: this.data.picList,
      picList2: this.data.picList2
    })
  },
  removeVideo(e) {
    this.data.videoSrc = ''
    this.data.videoCover = ''
    this.setData({
      videoCover: this.data.videoCover,
      videoSrc: this.data.videoSrc,
      userSelect: '' // 因为只有一个视频，所以删除的时候需要重新选择上传视频还是图片
    })
  },
  //获取图片信息
  getImageInfo1(item) {
    wx.getImageInfo({
      src: item,
      success: (res) => {
        this.setData({
          imageWidth: res.width,
          imageHeight: res.height
        })
        console.log('329')
        console.log(this.data.imageWidth)
      }
    })
  },
  //选择图片
  upload() {
    let that = this
    let sheetList = []
    if (this.data.userSelect === 'img') {
      wx.showModal({
        title: '提示',
        content: '请不要选择超过2m大小的图片，亲测某些机型会出现闪退问题！',
        showCancel: false,
        success: () => {
          wx.chooseImage({
            sizeType: ['compressed'],
            count: 9 - this.data.picList.length, // 默认9
            success: (res) => {
              res.tempFiles.forEach((item, index) => {
                this.data.picList.push(item.path)
              })
              this.setData({
                picList: this.data.picList
              })
            },
          })
        }
      })
    } else if (this.data.userSelect === 'video') {
      wx.chooseVideo({
        compressed: false,
        success: (res) => {
          this.data.videoSrc = res.tempFilePaths
          this.data.videoCover = res.tempFilePath
          this.setData({
            videoSrc: this.data.videoSrc,
            videoCover: this.data.videoCover
          })

        }
      })
    } else {
      sheetList.push('图片', '视频')
      wx.showActionSheet({
        itemList: sheetList,
        success: (action) => {
          if (action.tapIndex === 0) {
            wx.showModal({
              title: '提示',
              content: '请不要选择超过2m大小的图片，亲测某些机型会出现闪退问题！',
              showCancel: false,
              success: () => {
                wx.chooseImage({
                  sizeType: ['compressed'],
                  count: 9 - this.data.picList.length, // 默认9
                  success: (res) => {
                    console.log(res)
                    res.tempFiles.forEach((item, index) => {
                      // if (item.)
                      console.log(item)
                      this.data.picList.push(item.path) //插入原图                  
                    })
                    this.setData({
                      picList: this.data.picList,
                      userSelect: 'img'
                    })
                    console.log('442')
                    console.log(this.data.picList)
                    // console.log('358')
                    // console.log(this.data.picList)
                  },
                })
              }
            })
          } else if (action.tapIndex === 1) {
            wx.chooseVideo({
              compressed: false,
              success: (res) => {
                this.data.videoSrc = res.tempFilePath
                this.data.videoCover = res.tempFilePath
                this.setData({
                  videoSrc: this.data.videoSrc,
                  videoCover: this.data.videoCover,
                  userSelect: 'video'
                })
              }
            })
          }
        }
      })
    }
  },


  titleInput(e) {
    this.setData({
      'params.title': e.detail.value
    })
  },
  contentInput(e) {
    this.setData({
      'params.content': e.detail.value
    })
  },
  addressInput(e) {
    this.setData({
      'params.location': e.detail.value
    })
  },
  typeChange(e) {
    this.setData({
      'params.newsType': e.detail.value
    })
  },
  viewAuthChange(e) {
    this.setData({
      'params.auth': e.detail.value
    })
  },
  needChange(e) {
    console.log('412')
    console.log(Number(!!e.detail.value[0]))
    this.setData({
      'params.activityAuth': Number(!!e.detail.value[0])
    })
  },
  tabChange(e) {
    let type = e.currentTarget.dataset.type
    if (type == '0') {
      this.setData({
        actTab: type,
        leftpx: '0rpx',
        'params.newsType': type
      })
    } else {
      this.setData({
        actTab: type,
        leftpx: '357rpx',
        'params.newsType': type
      })
    }

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    slimglist2 = []
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //获取评论、新闻、活动是否审核的权限
    wx.teamApi.news.approvalstatus().then(res => {
      app.globalData.approvalstatus = res.data.result
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})